package com.woniu.adapter;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.outlet.dao.CustomerTypePoMapper;
import com.woniu.outlet.po.CustomerTypePo;
import com.woniu.outlet.rabbitmq.MessageRepo;
import com.woniu.outlet.redis.RedisRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CustomerTypeAdapter {

    @Autowired
    private CustomerTypePoMapper customerTypePoMapper;

    @Autowired
    private RedisRepo redisRepo;

    @Autowired
    private MessageRepo messageRepo;


    public List<CustomerTypePo> findCustomerTypes() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("customerType:list");
        List<CustomerTypePo> lists = new ArrayList<>();
        if (!StringUtils.isEmpty(str)) {
            lists = mapper.readValue(str, new TypeReference<List<CustomerTypePo>>() {
            });
            return lists;
        }
        lists = customerTypePoMapper.selectByExample(null);
        //存到redis
        redisRepo.saveRedisRepo("customerType:list",mapper.writeValueAsString(lists));
        return lists;
    }

    public CustomerTypePo getCustomerTypeById(Long id) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str = redisRepo.findRedisRepo("customerType:" + id);
        CustomerTypePo customerTypePo = null;
        if (!StringUtils.isEmpty(str)) {
            customerTypePo = mapper.readValue(str, new TypeReference<CustomerTypePo>() {
            });
            return customerTypePo;
        }
        customerTypePo = customerTypePoMapper.selectByPrimaryKey(id);
        //存到redis
        redisRepo.saveRedisRepo("customerType:"+id,mapper.writeValueAsString(customerTypePo));
        return customerTypePo;
    }

    public void addCustomerTypePo(CustomerTypePo customerTypePo){
        customerTypePoMapper.insert(customerTypePo);
        redisRepo.deleteRedisRepo("customerType:list");

    }

    public void updateCustomerTypePo(CustomerTypePo customerTypePo){
        customerTypePoMapper.updateByPrimaryKeySelective(customerTypePo);
        redisRepo.deleteRedisRepo("customerType:list");
    }

    public void deleteCustomerTypePoById(Long id){
        customerTypePoMapper.deleteByPrimaryKey(id);
        redisRepo.deleteRedisRepo("customerType:list");
    }
}
